import { nextTick } from 'vue'
import hasPermission from '@/utils/hasPermission'

/**
 * 按钮级别权限
 * 可传 string 或者 string[]
 * v-permission="[]"
 */
const authPermission = (el, binding) => {
  // 不应该出现重复值 - 防止多次执行
  if (JSON.stringify(binding.value) === JSON.stringify(binding.oldValue)) {
    return
  }

  const has = hasPermission(binding.value)

  // 无权限则移除按钮节点
  if (!has) {
    el.style.display = 'none'
    nextTick(() => {
      el.parentNode?.removeChild(el)
    })
  }
}

export const setupSetAuthDirective = (app) => {
  app.directive('permission', authPermission)
}
